import { OverlayRef } from '@angular/cdk/overlay';
import { Portal } from '@angular/cdk/portal';
import { doFnResult } from '../utils/result';
import { ExtendOverlayConfig } from './interface';

export class ExtendOverlayRef {
  listeners = [];

  portal: Portal<any>;
  extendConfig: ExtendOverlayConfig;
  constructor(public overlayRef: OverlayRef) {}

  destroyListener(): void {
    this.listeners.forEach((listener): void => {
      listener?.();
    });
  }

  destroy(result?): void {
    const _result = result ? result : null;
    this.overlayRef.dispose();
    this.destroyListener();
    this.extendConfig.afterClose?.(_result);
  }

  close(result?): void {
    const _result = result ? result : null;
    if (this.extendConfig?.beforeClose) {
      // Execute the callback function before closing (return: boolean | promise | undefined)
      const call = this.extendConfig.beforeClose(this, this.portal, _result);
      doFnResult(call, (res): void => {
        if (res) {
          // 火狐异常polyfill类名在打开时候存在，关闭时候需要去掉
          document.documentElement.classList.remove('cdk-firefox-polyfill');
          this.destroy(_result);
        }
      });
    } else {
      // 火狐异常polyfill类名在打开时候存在，关闭时候需要去掉
      document.documentElement.classList.remove('cdk-firefox-polyfill');
      this.destroy(_result);
    }
  }
}
